<template>
    <div class="app-container">
        <!-- <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                        <el-form-item label="设备编号" prop="machineId" style="width: 200px;">
                            <el-input
                                    v-model="queryParams.machineId"
                                    placeholder="请输入设备编号"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="设备名称" prop="machineName" style="width: 200px;">
                            <el-input
                                    v-model="queryParams.machineName"
                                    placeholder="请输入设备名称"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="车间" prop="facilityId" style="width: 200px;">
                            <el-select v-model="queryParams.facilityId" placeholder="请输入车间" clearable @change="facilityIdChange">
                                <el-option
                                        v-for="dict in factoryIdOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="制造区域" prop="area" style="width: 200px;">
                            <el-select v-model="queryParams.area" placeholder="请选择制造区域" clearable @change="areaChange">
                                <el-option
                                        v-for="dict in factoryAreaIdOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="制造类型" prop="modelType" style="width: 200px;">
                            <el-select v-model="queryParams.modelType" placeholder="请选择制造类型" clearable>
                                <el-option
                                        v-for="dict in listProductionTypeOptions"
                                        :key="dict.value"
                                        :label="dict.label"
                                        :value="dict.value"
                                />
                            </el-select>
                        </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>

                <el-button
                      type="warning"
                      plain
                      icon="Download"
                      @click="handleExport"
                      v-hasPermi="['SYSConfig:factorySite:export']"
              >导出</el-button>
            </el-form-item>
        </el-form> -->

        <el-col :span="1.5">
          </el-col>

        <!-- <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['SYSConfig:machine:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="info"
                        plain
                        icon="Sort"
                        @click="toggleExpandAll"
                >展开/折叠</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row> -->

        <!-- <el-table
                v-if="refreshTable"
                v-loading="loading"
                :data="machineList"
                row-key="machineId"
                :default-expand-all="isExpandAll"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                style="height: calc(100% - 75px)"
        >
                        <el-table-column label="id" prop="id" width="250"/>
                        <el-table-column label="父级节点" align="center" prop="pid" width="150"/>
                        <el-table-column label="是否有子节点" align="center" prop="hasChild" />
                        <el-table-column label="设备名称" align="center" prop="machineName" width="150"/>
                        <el-table-column label="车间号" align="center" prop="facilityId" />
                        <el-table-column label="线别" align="center" prop="lineId" />
                        <el-table-column label="图片" align="center" prop="img" />
                        <el-table-column label="备注" align="center" prop="remark" width="150"/>
                        <el-table-column label="状态" align="center" prop="status" />
                    <el-table-column label="制造区域" align="center" prop="area"/>
                        <el-table-column label="虚拟设备" align="center" prop="isVirtualMachine" />
                        <el-table-column label="分析源" align="center" prop="isAnalysis" />
                        <el-table-column label="分组" align="center" prop="groupTeam" width="150"/>
                    <el-table-column label="制造商" align="center" prop="manufacturer" />
                        <el-table-column label="优先级" align="center" prop="level" />
                        <el-table-column label="是否允许并联" align="center" prop="allowParallelConnection" />
                    <el-table-column label="设备类型" align="center" prop="machineType" />
                    <el-table-column label="制造类型" align="center" prop="modelType" />
                        <el-table-column label="镜像源设备" align="center" prop="mirrorMachine" />
                        <el-table-column label="排序" align="center" prop="no" />
                        <el-table-column label="新增字段1" align="center" />
                        <el-table-column label="新增字段2" align="center" />
                        <el-table-column label="新增字段3" align="center" />
                        <el-table-column label="新增字段4" align="center" />
                        <el-table-column label="新增字段5" align="center" />
        </el-table> -->

        <t-ag-grid
          :columnDefs="columnDefs"
          @grid-ready="onGridReady"
          :autoGroupColumnDef="autoGroupColumnDef"
          :rowData="data.rowData"
          :treeData="true"
          :animateRows="true"
          :groupDefaultExpanded="groupDefaultExpanded"
          :getDataPath="getDataPath"
          align="center"
          header-align="center"
          :defaultColDef = "{
            filter: true,
            menuTabs: ['filterMenuTab', 'columnsMenuTab']
          }"
        />

        <!-- 添加或修改设备情报对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="machineRef" :model="form" :rules="rules" label-width="80px">

              <h1>暂未开放！！！</h1>
                                <!-- <el-form-item label="id" prop="id">
                                    <el-input v-model="form.id" placeholder="请输入id" />
                                </el-form-item>
                                <el-form-item label="父级节点" prop="pid">
                                    <el-tree-select
                                            v-model="form.pid"
                                            :data="machineOptions"
                                            :props="{ value: 'machineId', label: 'machineName', children: 'children' }"
                                            value-key="machineId"
                                            placeholder="请选择父级节点"
                                            check-strictly
                                    />
                                </el-form-item>
                                <el-form-item label="是否有子节点" prop="hasChild">
                                    <el-input v-model="form.hasChild" placeholder="请输入是否有子节点" />
                                </el-form-item>
                                <el-form-item label="设备名称" prop="machineName">
                                    <el-input v-model="form.machineName" placeholder="请输入设备名称" />
                                </el-form-item>
                                <el-form-item label="车间号" prop="facilityId">
                                    <el-input v-model="form.facilityId" placeholder="请输入车间号" />
                                </el-form-item>
                                <el-form-item label="线别" prop="lineId">
                                    <el-input v-model="form.lineId" placeholder="请输入线别" />
                                </el-form-item>
                                <el-form-item label="备注" prop="remark">
                                    <el-input v-model="form.remark" placeholder="请输入备注" />
                                </el-form-item>
                                <el-form-item label="制造区域" prop="area">
                                    <el-select v-model="form.area" placeholder="请选择区域">
                                        <el-option
                                                v-for="dict in oee_b_factory_area"
                                                :key="dict.value"
                                                :label="dict.label"
                                                :value="dict.value"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="虚拟设备" prop="isVirtualMachine">
                                    <el-input v-model="form.isVirtualMachine" placeholder="请输入虚拟设备" />
                                </el-form-item>
                                <el-form-item label="分析源" prop="isAnalysis">
                                    <el-input v-model="form.isAnalysis" placeholder="请输入分析源" />
                                </el-form-item>
                                <el-form-item label="分组" prop="groupTeam">
                                    <el-input v-model="form.groupTeam" placeholder="请输入分组" />
                                </el-form-item>
                                <el-form-item label="制造商" prop="manufacturer">
                                    <el-checkbox-group v-model="form.manufacturer">
                                        <el-checkbox
                                                v-for="dict in oee_b_machine"
                                                :key="dict.value"
                                                :label="dict.value">
                                            {{dict.label}}
                                        </el-checkbox>
                                    </el-checkbox-group>
                                </el-form-item>
                                <el-form-item label="优先级" prop="level">
                                    <el-input v-model="form.level" placeholder="请输入优先级" />
                                </el-form-item>
                                <el-form-item label="是否允许并联" prop="allowParallelConnection">
                                    <el-input v-model="form.allowParallelConnection" placeholder="请输入是否允许并联" />
                                </el-form-item>
                                <el-form-item label="设备类型" prop="machineType">
                                    <el-checkbox-group v-model="form.machineType">
                                        <el-checkbox
                                                v-for="dict in oee_b_machine_type"
                                                :key="dict.value"
                                                :label="dict.value">
                                            {{dict.label}}
                                        </el-checkbox>
                                    </el-checkbox-group>
                                </el-form-item>
                                <el-form-item label="制造类型" prop="modelType">
                                    <el-radio-group v-model="form.modelType">
                                        <el-radio
                                                v-for="dict in oee_b_production_type"
                                                :key="dict.value"
                                                :label="dict.value"
                                        >{{dict.label}}</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item label="镜像源设备" prop="mirrorMachine">
                                    <el-input v-model="form.mirrorMachine" placeholder="请输入镜像源设备" />
                                </el-form-item>
                                <el-form-item label="排序" prop="no">
                                    <el-input v-model="form.no" placeholder="请输入排序" />
                                </el-form-item> -->
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
  </template>

  <script setup name="Machine">
  import { listMachine, getMachine, delMachine, addMachine, updateMachine } from "@/api/SYSConfig/machine"

  import { factoryIdOptions, factoryAreaIdOptions, listProductionTypeOptions } from '@/common/options'

  import { getFactoryAreaId, getModelType } from '@/common/affect'

  const { proxy } = getCurrentInstance()

  const machineList = ref([])
  const machineOptions = ref([])
  const open = ref(false)
  const loading = ref(true)
  const showSearch = ref(true)
  const title = ref("")
  const isExpandAll = ref(false)
  const refreshTable = ref(true)

  const data = reactive({
    form: {},
    queryParams: {
      machineId: null,
      machineName: null,
      facilityId: null,
      img: null,
      area: null,
      manufacturer: null,
      machineType: null,
      modelType: null
    },
    rules: {
      id: [
        { required: true, message: "id不能为空", trigger: "blur" }
      ],
      area: [
        { required: true, message: "区域不能为空", trigger: "change" }
      ]
    },
    rowData: []
  })

  const columnDefs = [
    // { headerName: "id", field: "id", minWidth: 100, flex: 1 },
    // { headerName: "父级节点", field: "pid", minWidth: 120, flex: 1 },
    // { headerName: "是否有子节点", field: "hasChild", minWidth: 100, flex: 1 },
    { headerName: "设备名称", field: "machineName", minWidth: 150, flex: 1 },
    { headerName: "车间号", field: "facilityId", minWidth: 70, flex: 1 },
    { headerName: "线别", field: "lineId", minWidth: 70, flex: 1 },
    // { headerName: "图片", field: "img", minWidth: 70, flex: 1 },
    // { headerName: "备注", field: "remark", minWidth: 110, flex: 1 },
    // { headerName: "状态", field: "status", minWidth: 70, flex: 1 },
    { headerName: "制造区域", field: "area", minWidth: 70, flex: 1 },
    { headerName: "虚拟设备", field: "isVirtualMachine", minWidth: 70, flex: 1 },
    { headerName: "分析源", field: "isAnalysis", minWidth: 70, flex: 1 },
    // { headerName: "分组", field: "groupTeam", minWidth: 100, flex: 1 },
    { headerName: "制造商", field: "manufacturer", minWidth: 70, flex: 1 },
    // { headerName: "优先级", field: "level", minWidth: 70, flex: 1 },
    // { headerName: "是否允许并联", field: "allowParallelConnection", minWidth: 90, flex: 1 },
    { headerName: "设备类型", field: "machineType", minWidth: 80, flex: 1 },
    { headerName: "生产类型", field: "modelType", minWidth: 80, flex: 1 },
    { headerName: "镜像源设备", field: "mirrorMachine", minWidth: 70, flex: 1 },
    { headerName: "排序", field: "no", minWidth: 70, flex: 1 }
    // { headerName: "新增字段1", field: "", minWidth: 70, flex: 1 }
  ]

  const autoGroupColumnDef = {
    headerName: '设备ID',
    minWidth: 100,
    cellRendererParams: {
      suppressCount: true
    }
  }

  const getDataPath = (data) => {
    return data.orgHierarchy
  }

  const groupDefaultExpanded = 0 // 需要展开的等级 0：只展开父级  1： 父 + 一级子 。。。

  const { queryParams, form, rules } = toRefs(data)

  /** 查询设备情报列表 */
  function getList() {
    loading.value = true
    listMachine(queryParams.value).then(response => {
      let _target = []
      //   machineList.value = proxy.handleTree(response.data, "machineId", "pid")
      data.rowData = response.data.map((item) => {
        if(item.pid === '0'){
          _target = [item.id]
        } else {
          if(item.pid === _target[_target.length - 1]){
            _target.push(item.id)
          } else {
            let _temp = _target.findIndex((val) => {
              return val === item.pid
            })
            _target.length = _temp + 1
            _target.push(item.id)
          }
        }
        item.orgHierarchy = JSON.parse(JSON.stringify(_target))
        return item

      })
      loading.value = false
    })
  }

  function handleExport() {
    proxy.download('SYSConfig/machine/export', {
      ...data.queryParams
    }, `factorySite_${new Date().getTime()}.xlsx`)
  }

  /** 查询设备情报下拉树结构 */
  function getTreeselect() {
    listMachine().then(response => {
      machineOptions.value = []
      const data = { machineId: 0, machineName: '顶级节点', children: [] }
      data.children = proxy.handleTree(response.data, "machineId", "pid")
      machineOptions.value.push(data)
    })
  }

  // 取消按钮
  function cancel() {
    open.value = false
    reset()
  }

  // 表单重置
  function reset() {
    form.value = {
      machineId: null,
      id: null,
      pid: null,
      hasChild: null,
      machineName: null,
      facilityId: null,
      lineId: null,
      img: null,
      remark: null,
      status: null,
      area: null,
      isVirtualMachine: null,
      isAnalysis: null,
      groupTeam: null,
      manufacturer: [],
      level: null,
      allowParallelConnection: null,
      machineType: [],
      modelType: null,
      mirrorMachine: null,
      no: null
    }
    proxy.resetForm("machineRef")
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    getList()
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef")
    handleQuery()
  }

  /** 新增按钮操作 */
  function handleAdd(row) {
    reset()
    getTreeselect()
    if (row != null && row.machineId) {
      form.value.pid = row.machineId
    } else {
      form.value.pid = 0
    }
    open.value = true
    title.value = "添加设备情报"
  }

  /** 展开/折叠操作 */
  function toggleExpandAll() {
    refreshTable.value = false
    isExpandAll.value = !isExpandAll.value
    nextTick(() => {
      refreshTable.value = true
    })
  }

  /** 修改按钮操作 */
  async function handleUpdate(row) {
    reset()
    await getTreeselect()
    if (row != null) {
      form.value.pid = row.pid
    }
    getMachine(row.machineId).then(response => {
      form.value = response.data
      form.value.manufacturer = form.value.manufacturer.split(",")
      form.value.machineType = form.value.machineType.split(",")
      open.value = true
      title.value = "修改设备情报"
    })
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["machineRef"].validate(valid => {
      if (valid) {
        form.value.manufacturer = form.value.manufacturer.join(",")
        form.value.machineType = form.value.machineType.join(",")
        if (form.value.machineId != null) {
          updateMachine(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          })
        } else {
          addMachine(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
        }
      }
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    proxy.$modal.confirm('是否确认删除设备情报编号为"' + row.machineId + '"的数据项？').then(function() {
      return delMachine(row.machineId)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {})
  }

  /**
   * 级联
   *
   * 制造区域
   */
  const facilityIdChange = () => {
    getFactoryAreaId({
      factory: queryParams.value.facilityId
    }).then((res) => {
      queryParams.value.area = null
      factoryAreaIdOptions.value = []
      res.rows.forEach(item => {
        factoryAreaIdOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  /**
   * 级联
   *
   * 制造类型
   */
  const areaChange = () => {
    getModelType({
      factoryAreaIdList: queryParams.value.area
    }).then((res) => {
      queryParams.value.modelType = null
      listProductionTypeOptions.value = []
      res.rows.forEach(item => {
        listProductionTypeOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  getList()
  </script>
